package org.vaadin.html5dropzone;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.vaadin.html5dropzone.widgetset.client.ui.VHtml5DropZone.DataFlawor;

import sun.misc.BASE64Decoder;

import com.vaadin.Application;
import com.vaadin.terminal.StreamResource;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.terminal.StreamResource.StreamSource;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Layout;
import com.vaadin.ui.Window;

@SuppressWarnings("serial")
public class Html5dropzoneApplication extends Application {
	@Override
	public void init() {
		Window mainWindow = new Window("Html5dropzone Application");
		mainWindow.setTheme("runo");
		Label label = new Label("Hello Vaadin user");
		mainWindow.addComponent(label);
		setMainWindow(mainWindow);

		Html5DropZone html5DropZone = new Html5DropZone();
		html5DropZone.setCaption("Drop your stuff here, even files with FF 36 (try png or text files)");
		mainWindow.addComponent(html5DropZone);

		final Layout droppedData = new CssLayout();
		droppedData.setCaption("Dragged data will appear here:");
		mainWindow.addComponent(droppedData);

		html5DropZone.setDropHandler(new DropHandler() {

			public void receive(Transferrable transferrable) {

				Label l = new Label();
				l.setSizeUndefined();

				String text = (String) transferrable.getData(DataFlawor.TEXT);
				if (text != null && !"".equals(text)) {
					l.setValue(text);
				}

				String data = (String) transferrable
						.getData(DataFlawor.FILE_CONTENTS_TEXT);
				if (data != null) {
					if (data.contains("image/png")) {

						BASE64Decoder base64Decoder = new BASE64Decoder();
						try {
							final byte[] decodeBuffer = base64Decoder
									.decodeBuffer(data.substring(22));

							StreamSource str = new StreamSource() {
								public InputStream getStream() {
									return new ByteArrayInputStream(
											decodeBuffer);
								}
							};

							StreamResource streamResource = new StreamResource(
									str, "image.png",
									Html5dropzoneApplication.this);
							streamResource.setMIMEType("image/png");

							l.setIcon(streamResource);

						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					} else {

						l.setCaption("HTML 5 drop contained a file");
						l.setIcon(new ThemeResource("icons/16/document.png"));
						BASE64Decoder base64Decoder = new BASE64Decoder();
						try {
							byte[] decodeBuffer = base64Decoder
									.decodeBuffer(data.substring(23));
							String string = new String(decodeBuffer);
							l.setValue(string);

						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				droppedData.addComponent(l);
			}
		});

	}
}
